import axios from "axios"
import swal from 'sweetalert2'

const service = axios.create({
    baseURL: "http://localhost:3000/",
    timeout: 30000,
})

//post请求头设置
service.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';

//请求拦截器，目的是为了在请求头上带上token
service.interceptors.request.use(
    config => {
        if (localStorage.getItem('Authorization')) {
            //token字段是要和后端协商好的
            config.headers.common["token"] = localStorage.getItem('Authorization');
            // debugger
        }
        return config;
    },
    error => {
        return Promise.reject(error);
    }
);

//响应拦截器
service.interceptors.response.use(
    response => {
        //请求正常则返回
        if (response.status == 200) {
            if (response.data.code == 0) {
                return Promise.resolve(response.data)
                
            }else{
                swal({
                    timer: 1500,
                    type: "error",
                    text: response.data.msg
                })
                return Promise.reject(response.data)
            }
            
        }
    },
    error => {
        // 请求错误则向store commit这个状态变化
        console.log(error);
        swal({
            timer: 1500,
            type: "error",
            text: error
        })
        return Promise.reject(error)
    }
)

export default service